package me.android.library.common.orm.ability;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.google.common.collect.Lists;

import java.util.List;

import cn.hutool.db.meta.Column;
import cn.hutool.db.meta.Table;

public interface DsAdmin extends DS {

    default String getDatabaseName() {
        return getHelper().getDatabaseName();
    }

    default int getVersion() {
        try (SQLiteDatabase db = readableDb()) {
            return db.getVersion();
        }
    }

    default String getPath() {
        try (SQLiteDatabase db = readableDb()) {
            return db.getPath();
        }
    }

    default List<String> getTables() {
        String sql = "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%';";
        List<String> tableNames = Lists.newArrayList();
        try (SQLiteDatabase db = readableDb();
             Cursor cursor = db.rawQuery(sql, null)) {
            while (cursor.moveToNext()) {
                tableNames.add(cursor.getString(0));
            }
        }

        return tableNames;
    }

    default Table getTableInfo(String tableName) {
        String sql = String.format("PRAGMA table_info(%s)", tableName);
        Table table = Table.create(tableName);
        try (SQLiteDatabase db = readableDb();
             Cursor cursor = db.rawQuery(sql, null)) {

            Column column = new Column();
            table.setColumn(column);

            int index;
            while (cursor.moveToNext()) {
                index = cursor.getColumnIndex("cid");
                int cid = cursor.getInt(index);

                index = cursor.getColumnIndex("name");
                String name = cursor.getString(index);

                index = cursor.getColumnIndex("type");
                String type = cursor.getString(index);

                index = cursor.getColumnIndex("notnull");
                int notNull = cursor.getInt(index);

                index = cursor.getColumnIndex("dflt_value");
                String defaultValue = cursor.getString(index);

                index = cursor.getColumnIndex("pk");
                int isPk = cursor.getInt(index);

                column.setName(name)
                        .setTypeName(type)
                        .setNullable(notNull == 0)
                        .setPk(isPk == 1)
                        .setColumnDef(defaultValue);
            }
        }

        return table;
    }

}
